package com.dd.cloud.user.service.paynotice.promode.notice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dd.cloud.common.config.obs.PathProperties;
import com.dd.cloud.common.constants.ConsultConstants;
import com.dd.cloud.common.constants.TemplateConstants;
import com.dd.cloud.common.constants.UserConstants;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.entity.consult.ConsultSubscribe;
import com.dd.cloud.user.entity.doctor.DoctorDetail;
import com.dd.cloud.user.entity.order.OrderPay;
import com.dd.cloud.user.mq.MQConfig;
import com.dd.cloud.user.mq.RabbitSend;
import com.dd.cloud.user.req.consult.ImCreateUserReq;
import com.dd.cloud.user.service.consule.IConsultSubscribeService;
import com.dd.cloud.user.service.consule.ITencentImMsgService;
import com.dd.cloud.user.service.doctor.IDoctorDetailService;
import com.dd.cloud.user.service.doctor.IDoctorOrderIncomeDetailService;
import com.dd.cloud.user.service.log.ILogErrorService;
import com.dd.cloud.user.service.paynotice.promode.NoticeService;
import com.dd.cloud.user.service.paynotice.promode.NoticeType;
import com.zk.pay.constants.CS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 支付单次预约产品回调
 */
@NoticeType(source = CS.NOTICE_SOURCE.PAY, proType = CS.NOTICE_CHANNEL.SINGLE)
@Slf4j
public class ConsultPayNoticeService implements NoticeService {
    @Autowired
    private IConsultSubscribeService consultSubscribeService;
    @Autowired
    private ILogErrorService logErrorService;
    @Autowired
    private IDoctorOrderIncomeDetailService doctorOrderIncomeDetailService;

    @Autowired
    private IDoctorDetailService doctorDetailService;

    @Autowired
    private RabbitSend rabbitSend;
    @Autowired
    private ITencentImMsgService tencentImMsgService;
    @Autowired
    private PathProperties pathProperties;


    /**
     * 支付回调处理逻辑 预约咨询问诊的回调, 修改业务数据状态
     *
     * @param request
     * @param orderPay 订单对象
     * @param flowNo   流水编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async
    public void notice(HttpServletRequest request, OrderPay orderPay, String flowNo) {
        try {
            String serverNo = orderPay.getServerNo();
            ConsultSubscribe consultSubscribe = consultSubscribeService.getById(Integer.valueOf(serverNo));
            UpdateWrapper<ConsultSubscribe> uw = new UpdateWrapper<>();
            uw.lambda().eq(ConsultSubscribe::getId, consultSubscribe.getId())
                    .set(ConsultSubscribe::getStatus, ConsultConstants.Status.SUBMIT);
            boolean update = consultSubscribeService.update(uw);
            if (!update) {
                logErrorService.presBackLog("预约回调修改状态数据失败", "预约支付回调异常", "serverNo=" + orderPay.getServerNo());
            }

            try {
                /**
                 * 支付成功后创建im聊天用户, im体验版用户数只有100, 支付成功后才创建用户
                 * im账号 医生为 医生id_医生登录类型  就诊人为 患者账号id_患者登录类型_就诊卡id
                 */
                QueryWrapper<DoctorDetail> qd = new QueryWrapper<>();
                qd.lambda().eq(DoctorDetail::getDoctorId, consultSubscribe.getDoctorId())
                        .eq(DoctorDetail::getStatus, UserConstants.DoctorDetailStatus.NORMAL);
                DoctorDetail doctorDetail = doctorDetailService.getOne(qd);
                if (doctorDetail == null) {
                    throw new ZekeException("医生信息为空");
                }

                List<ImCreateUserReq> imCreateUserReqList = new ArrayList<>();
                ImCreateUserReq createDoctorUserReq = new ImCreateUserReq();
                createDoctorUserReq.setUserId(consultSubscribe.getDoctorId());
                createDoctorUserReq.setUserType(LoginInfo.UserType.DOCTOR);
                createDoctorUserReq.setUserName(doctorDetail.getName());
                createDoctorUserReq.setFaceUrl(doctorDetail.getAvatar());
                if (!StringUtils.isBlank(doctorDetail.getAvatar()) && !doctorDetail.getAvatar().startsWith("http")){
                    createDoctorUserReq.setFaceUrl(pathProperties.getImageServer() + doctorDetail.getAvatar());
                }
                imCreateUserReqList.add(createDoctorUserReq);
                ImCreateUserReq createPatientUserReq = new ImCreateUserReq();
                createPatientUserReq.setUserId(consultSubscribe.getPatientId());
                createPatientUserReq.setUserType(LoginInfo.UserType.PATIENT);
                createPatientUserReq.setUserName(consultSubscribe.getPatientName());
                //就诊人无头像,先用固定默认头像 男女分开
                createPatientUserReq.setFaceUrl("https://zk-ak.obs.cn-south-1.myhuaweicloud.com/dadao/img_man.png");
                if ("女".equals(consultSubscribe.getPatientSex())){
                    createPatientUserReq.setFaceUrl("https://zk-ak.obs.cn-south-1.myhuaweicloud.com/dadao/img_woman.png");
                }
                createPatientUserReq.setMedId(consultSubscribe.getMedId());
                imCreateUserReqList.add(createPatientUserReq);
                tencentImMsgService.imCreateImUser(imCreateUserReqList);
            } catch (ZekeException ze) {
                ze.printStackTrace();
                logErrorService.presBackLog("添加im用户异常", "预约支付回调异常", "serverNo=" + orderPay.getServerNo());

            }

            log.info("支付成功增加问诊收入明细日志");
            doctorOrderIncomeDetailService.addConsultOrderIncomeDetail(orderPay);
            String params = TemplateConstants.TemplateType.NINE_TYPE + "-" + orderPay.getOrderNo();
            log.info("支付成功发送模板消息,参数为{}", params);
            rabbitSend.sendMessage(MQConfig.TEMPLATE_EXCHANGE, MQConfig.TEMPLATE_QUEUE, params);
        } catch (Exception e) {
            e.printStackTrace();
            logErrorService.presBackLog("预约回调抛异常", "预约支付回调异常", "serverNo=" + orderPay.getServerNo());
        }

    }
}
